// Package version 提供版本信息管理
package version

import (
	"runtime/debug"
	"strings"
)

const (
	// DefaultVersion 默认版本号
	DefaultVersion = "1.2.0"
)

// GetVersion 获取版本信息
// 优先从构建信息中获取，如果获取失败则使用默认版本
func GetVersion() string {
	// 尝试从构建信息获取版本
	if info, ok := debug.ReadBuildInfo(); ok {
		// 查找版本信息
		for _, setting := range info.Settings {
			if setting.Key == "vcs.revision" && len(setting.Value) >= 7 {
				// 如果是git commit hash，取前7位
				return DefaultVersion + "+" + setting.Value[:7]
			}
		}

		// 如果有Main模块版本信息
		if info.Main.Version != "" && info.Main.Version != "(devel)" {
			return info.Main.Version
		}
	}

	// 返回默认版本
	return DefaultVersion
}

// GetBuildInfo 获取构建信息
func GetBuildInfo() map[string]string {
	buildInfo := make(map[string]string)
	buildInfo["version"] = GetVersion()

	if info, ok := debug.ReadBuildInfo(); ok {
		// 添加Go版本信息
		buildInfo["go_version"] = info.GoVersion

		// 添加构建设置
		for _, setting := range info.Settings {
			switch setting.Key {
			case "vcs.revision":
				if len(setting.Value) >= 7 {
					buildInfo["commit"] = setting.Value[:7]
				}
			case "vcs.time":
				buildInfo["build_time"] = setting.Value
			case "vcs.modified":
				buildInfo["modified"] = setting.Value
			}
		}
	}

	return buildInfo
}

// GetVersionString 获取格式化的版本字符串
func GetVersionString() string {
	version := GetVersion()
	buildInfo := GetBuildInfo()

	var parts []string
	parts = append(parts, "v"+version)

	if commit, ok := buildInfo["commit"]; ok {
		parts = append(parts, commit)
	}

	if modified, ok := buildInfo["modified"]; ok && modified == "true" {
		parts = append(parts, "modified")
	}

	return strings.Join(parts, "-")
}
